import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'edit_logic.dart';
import 'edit_state.dart';

/// 编辑页面视图 - Edit Page View
///
/// 提供富文本编辑器、属性面板、模板变量管理等功能
/// Provides rich text editor, property panel, template variable management
class EditPage extends StatelessWidget {
  const EditPage({super.key});

  @override
  Widget build(BuildContext context) {
    // GetBuilder作为最外层包裹Widget - GetBuilder as the outermost wrapper widget
    // 每个View中只能有一个GetBuilder - Only one GetBuilder per View
    return GetBuilder<EditLogic>(
      init: EditLogic(),
      builder: (logic) => Scaffold(
        appBar: _buildAppBar(logic, logic.state),
        body: _buildBody(logic, logic.state),
        bottomNavigationBar: _buildBottomBar(logic, logic.state),
      ),
    );
  }

  /// 构建应用栏 - Build App Bar
  PreferredSizeWidget _buildAppBar(EditLogic logic, EditState state) {
    return AppBar(
      title: Text(
        state.isNewPrompt.value ? '新建 Prompt' : '编辑 Prompt',
        style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
      ),
      actions: [
        // 预览模式切换 - Preview Mode Toggle
        IconButton(
          icon: Icon(
            state.isPreviewMode.value ? Icons.edit : Icons.preview,
            color: state.isPreviewMode.value ? Colors.blue : null,
          ),
          onPressed: logic.togglePreviewMode,
          tooltip: state.isPreviewMode.value ? '编辑模式' : '预览模式',
        ),

        // 保存按钮 - Save Button
        IconButton(
          icon: const Icon(Icons.save),
          onPressed: state.hasUnsavedChanges.value ? logic.savePrompt : null,
          tooltip: '保存',
        ),

        // 更多选项 - More Options
        PopupMenuButton<String>(
          onSelected: logic.handleMenuAction,
          itemBuilder: (context) => [
            const PopupMenuItem(
              value: 'export',
              child: ListTile(
                leading: Icon(Icons.file_download),
                title: Text('导出'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            const PopupMenuItem(
              value: 'duplicate',
              child: ListTile(
                leading: Icon(Icons.copy),
                title: Text('复制'),
                contentPadding: EdgeInsets.zero,
              ),
            ),
            const PopupMenuItem(
              value: 'delete',
              child: ListTile(
                leading: Icon(Icons.delete, color: Colors.red),
                title: Text('删除', style: TextStyle(color: Colors.red)),
                contentPadding: EdgeInsets.zero,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建主体内容 - Build Body Content
  Widget _buildBody(EditLogic logic, EditState state) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final screenWidth = constraints.maxWidth;
        final showRightPanel = screenWidth > 800;
        
        return Row(
          children: [
            // 主编辑区域 - Main Edit Area
            Expanded(
              flex: showRightPanel ? 3 : 1,
              child: _buildMainEditArea(logic, state),
            ),

            // 右侧面板 - Right Panel
            if (showRightPanel)
              SizedBox(
                width: (320.0).clamp(200.0, screenWidth * 0.3),
                child: Container(
                  decoration: BoxDecoration(
                    border: Border(left: BorderSide(color: Colors.grey.shade300)),
                  ),
                  child: _buildRightPanel(logic, state),
                ),
              ),
          ],
        );
      },
    );
  }

  /// 构建主编辑区域 - Build Main Edit Area
  Widget _buildMainEditArea(EditLogic logic, EditState state) {
    return Obx(() => state.isPreviewMode.value
        ? _buildPreviewArea(logic, state)
        : _buildEditorArea(logic, state));
  }

  /// 构建编辑器区域 - Build Editor Area
  Widget _buildEditorArea(EditLogic logic, EditState state) {
    return Column(
      children: [
        // 工具栏 - Toolbar
        _buildToolbar(logic, state),

        // 编辑器 - Editor
        Expanded(
          child: Container(
            padding: const EdgeInsets.all(16),
            child: TextField(
              controller: state.contentController,
              maxLines: null,
              expands: true,
              decoration: const InputDecoration(
                hintText:
                    '在这里输入您的 Prompt 内容...\n\n支持 Markdown 语法和模板变量 {{variable}}',
                border: InputBorder.none,
                contentPadding: EdgeInsets.zero,
              ),
              style: const TextStyle(
                fontSize: 16,
                height: 1.6,
                fontFamily: 'Consolas',
              ),
              onChanged: logic.onContentChanged,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建预览区域 - Build Preview Area
  Widget _buildPreviewArea(EditLogic logic, EditState state) {
    return Container(
      padding: const EdgeInsets.all(16),
      child: SingleChildScrollView(
        child: Obx(() => Text(
              state.contentController.text.isEmpty
                  ? '预览内容将在这里显示...'
                  : state.contentController.text,
              style: const TextStyle(fontSize: 16, height: 1.6),
            )),
      ),
    );
  }

  /// 构建工具栏 - Build Toolbar
  Widget _buildToolbar(EditLogic logic, EditState state) {
    return Container(
      height: 48,
      padding: const EdgeInsets.symmetric(horizontal: 8),
      decoration: BoxDecoration(
        color: Colors.grey.shade50,
        border: Border(bottom: BorderSide(color: Colors.grey.shade300)),
      ),
      child: LayoutBuilder(
        builder: (context, constraints) {
          final screenWidth = constraints.maxWidth;
          final isNarrow = screenWidth < 600;
          
          return SingleChildScrollView(
            scrollDirection: Axis.horizontal,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                // 格式化按钮 - Format Buttons
                if (!isNarrow || screenWidth > 400) ...[
                  IconButton(
                    icon: const Icon(Icons.format_bold),
                    onPressed: () => logic.insertFormat('**', '**'),
                    tooltip: '粗体',
                  ),
                  IconButton(
                    icon: const Icon(Icons.format_italic),
                    onPressed: () => logic.insertFormat('*', '*'),
                    tooltip: '斜体',
                  ),
                  IconButton(
                    icon: const Icon(Icons.code),
                    onPressed: () => logic.insertFormat('`', '`'),
                    tooltip: '代码',
                  ),
                  const VerticalDivider(),
                ],

                // 插入按钮 - Insert Buttons
                if (!isNarrow || screenWidth > 500) ...[
                  IconButton(
                    icon: const Icon(Icons.link),
                    onPressed: logic.insertLink,
                    tooltip: '插入链接',
                  ),
                  IconButton(
                    icon: const Icon(Icons.image),
                    onPressed: logic.insertImage,
                    tooltip: '插入图片',
                  ),
                  IconButton(
                    icon: const Icon(Icons.table_chart),
                    onPressed: logic.insertTable,
                    tooltip: '插入表格',
                  ),
                  const VerticalDivider(),
                ],

                // 模板变量 - Template Variables
                IconButton(
                  icon: const Icon(Icons.add_box),
                  onPressed: logic.insertVariable,
                  tooltip: '插入变量',
                ),

                const SizedBox(width: 16),

                // 字数统计 - Word Count
                Obx(() => Container(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      decoration: BoxDecoration(
                        color: Colors.grey.shade200,
                        borderRadius: BorderRadius.circular(12),
                      ),
                      child: Text(
                        '${state.wordCount.value} 字',
                        style: TextStyle(
                          fontSize: 12,
                          color: Colors.grey.shade600,
                        ),
                      ),
                    )),
              ],
            ),
          );
        },
      ),
    );
  }

  /// 构建右侧面板 - Build Right Panel
  Widget _buildRightPanel(EditLogic logic, EditState state) {
    return DefaultTabController(
      length: 3,
      child: Column(
        children: [
          // 标签栏 - Tab Bar
          const TabBar(
            tabs: [
              Tab(text: '属性'),
              Tab(text: '变量'),
              Tab(text: '版本'),
            ],
          ),

          // 标签内容 - Tab Content
          Expanded(
            child: TabBarView(
              children: [
                _buildPropertiesPanel(logic, state),
                _buildVariablesPanel(logic, state),
                _buildVersionsPanel(logic, state),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建属性面板 - Build Properties Panel
  Widget _buildPropertiesPanel(EditLogic logic, EditState state) {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 标题 - Title
          TextField(
            controller: state.titleController,
            decoration: const InputDecoration(
              labelText: '标题',
              hintText: '输入 Prompt 标题',
              border: OutlineInputBorder(),
            ),
            onChanged: logic.onTitleChanged,
          ),

          const SizedBox(height: 16),

          // 描述 - Description
          TextField(
            controller: state.descriptionController,
            maxLines: 3,
            decoration: const InputDecoration(
              labelText: '描述',
              hintText: '输入 Prompt 描述',
              border: OutlineInputBorder(),
            ),
            onChanged: logic.onDescriptionChanged,
          ),

          const SizedBox(height: 16),

          // 分类 - Category
          Obx(() => DropdownButtonFormField<String>(
                value: state.selectedCategory.value.isEmpty
                    ? null
                    : state.selectedCategory.value,
                decoration: const InputDecoration(
                  labelText: '分类',
                  border: OutlineInputBorder(),
                ),
                items: state.categories
                    .map((category) => DropdownMenuItem(
                          value: category,
                          child: Text(category),
                        ))
                    .toList(),
                onChanged: logic.onCategoryChanged,
                  )),

          const SizedBox(height: 16),

          // 标签 - Tags
          const Text('标签',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
          const SizedBox(height: 8),
          Obx(() => Wrap(
                spacing: 8,
                runSpacing: 8,
                children: [
                  ...state.selectedTags.map((tag) => Chip(
                        label: Text(tag),
                        onDeleted: () => logic.removeTag(tag),
                        deleteIcon: const Icon(Icons.close, size: 18),
                      )),
                  ActionChip(
                    label: const Text('+ 添加标签'),
                    onPressed: logic.showAddTagDialog,
                  ),
                ],
              )),

          const SizedBox(height: 16),

          // 文件格式 - File Format
          const Text('文件格式',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w500)),
          const SizedBox(height: 8),
          Obx(() => Column(
                children: ['md', 'txt', 'doc', 'pdf']
                    .map((format) => RadioListTile<String>(
                          title: Text(format.toUpperCase()),
                          value: format,
                          groupValue: state.selectedFormat.value,
                          onChanged: logic.onFormatChanged,
                          contentPadding: EdgeInsets.zero,
                        ))
                    .toList(),
              )),
        ],
      ),
    );
  }

  /// 构建变量面板 - Build Variables Panel
  Widget _buildVariablesPanel(EditLogic logic, EditState state) {
    return Column(
      children: [
        // 添加变量按钮 - Add Variable Button
        Padding(
          padding: const EdgeInsets.all(16),
          child: SizedBox(
            width: double.infinity,
            child: ElevatedButton.icon(
              onPressed: logic.addVariable,
              icon: const Icon(Icons.add),
              label: const Text('添加变量'),
            ),
          ),
        ),

        // 变量列表 - Variables List
        Expanded(
          child: Obx(() => ListView.builder(
                itemCount: state.variables.length,
                itemBuilder: (context, index) {
                  final variable = state.variables[index];
                  return Card(
                    margin:
                        const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                    child: Padding(
                      padding: const EdgeInsets.all(12),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Expanded(
                                child: Text(
                                  '{{${variable.name}}}',
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontFamily: 'Consolas',
                                  ),
                                ),
                              ),
                              IconButton(
                                icon: const Icon(Icons.delete, size: 20),
                                onPressed: () => logic.removeVariable(index),
                              ),
                            ],
                          ),
                          if (variable.description.isNotEmpty) ...[
                            const SizedBox(height: 4),
                            Text(
                              variable.description,
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey.shade600,
                              ),
                            ),
                          ],
                          if (variable.defaultValue.isNotEmpty) ...[
                            const SizedBox(height: 4),
                            Text(
                              '默认值: ${variable.defaultValue}',
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey.shade600,
                              ),
                            ),
                          ],
                        ],
                      ),
                    ),
                  );
                },
              )),
        ),
      ],
    );
  }

  /// 构建版本面板 - Build Versions Panel
  Widget _buildVersionsPanel(EditLogic logic, EditState state) {
    return Column(
      children: [
        // 版本信息 - Version Info
        Container(
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                 children: [
                   const Text('当前版本: ',
                       style: TextStyle(fontWeight: FontWeight.w500)),
                   Obx(() => Text('v${state.currentVersion.value}')),
                 ],
               ),
               const SizedBox(height: 8),
               Row(
                 children: [
                   const Text('总版本数: ',
                       style: TextStyle(fontWeight: FontWeight.w500)),
                   Obx(() => Text('${state.totalVersions.value}')),
                 ],
               ),
            ],
          ),
        ),

        const Divider(),

        // 版本操作按钮 - Version Action Buttons
        Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16),
          child: Row(
            children: [
              Expanded(
                child: OutlinedButton.icon(
                  onPressed: logic.viewVersionHistory,
                  icon: const Icon(Icons.history),
                  label: const Text('版本历史'),
                ),
              ),
              const SizedBox(width: 8),
              Expanded(
                child: OutlinedButton.icon(
                  onPressed: logic.compareVersions,
                  icon: const Icon(Icons.compare_arrows),
                  label: const Text('版本对比'),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 构建底部栏 - Build Bottom Bar
  Widget? _buildBottomBar(EditLogic logic, EditState state) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final screenWidth = constraints.maxWidth;
        
        // 移动端显示底部工具栏 - Show bottom toolbar on mobile
        if (screenWidth <= 800) {
          return BottomAppBar(
            child: SafeArea(
              child: Padding(
                padding: const EdgeInsets.symmetric(horizontal: 8),
                child: Row(
                  children: [
                    IconButton(
                      icon: const Icon(Icons.settings),
                      onPressed: logic.showPropertiesPanel,
                      tooltip: '属性',
                    ),
                    IconButton(
                      icon: const Icon(Icons.code),
                      onPressed: logic.showVariablesPanel,
                      tooltip: '变量',
                    ),
                    IconButton(
                      icon: const Icon(Icons.history),
                      onPressed: logic.viewVersionHistory,
                      tooltip: '版本',
                    ),
                    const Spacer(),
                    Obx(() => Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.grey.shade200,
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Text(
                            '${state.wordCount.value} 字',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey.shade600,
                            ),
                          ),
                        )),
                  ],
                ),
              ),
            ),
          );
        }
        return const SizedBox.shrink();
      },
    );
  }
}
